//
//  PhotoBrowserController.swift
//  XLWB
//
//  Created by 郭亮 on 16/3/22.
//  Copyright © 2016年 gl. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

private let photoBrowserCellId = "PhotoBrowserCellId"

class PhotoBrowserController: UIViewController {
    
    // MARK:-属性
    private var index: NSIndexPath?
    private var pictureUrls: [NSURL]?
    private lazy var collectionV: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserCollectionViewLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", bgColor: UIColor.lightGrayColor(), fontsize: 14)
    private lazy var saveButton: UIButton = UIButton(title: "保存", bgColor: UIColor.lightGrayColor(), fontsize: 14)
    
    
    // MARK:-自定义构造函数
    init(index: NSIndexPath, pictureUrls: [NSURL]) {
        super.init(nibName: nil, bundle: nil)
        self.index = index
        self.pictureUrls = pictureUrls
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //滚动到指定的item
        collectionV.scrollToItemAtIndexPath(index!, atScrollPosition: .Left, animated: false)
    }
    
    override func loadView() {
        super.loadView()
        view.bounds.size.width += 20
    }
}

// MARK:-设置UI
extension PhotoBrowserController {
    private func setupUI() {
        //添加子控制器
        view.addSubview(collectionV)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //设置frame
        collectionV.frame = view.bounds
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(-20)
            make.bottom.equalTo(-20)
            make.size.equalTo(closeButton.snp_size)
        }
        //设置属性
        collectionV.dataSource = self
        collectionV.registerClass(PhotoBrowserCollectionViewCell.self, forCellWithReuseIdentifier: photoBrowserCellId)
        closeButton.addTarget(self, action: "closeBtnClick", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "saveBtnClick", forControlEvents: .TouchUpInside)
    }
}

// MARK:-事件监听
extension PhotoBrowserController {
    @objc private func closeBtnClick() {
    dismissViewControllerAnimated(false, completion: nil)
    }
    
    @objc private func saveBtnClick() {
        //取出当前cell
        let cell = collectionV.visibleCells().first as! PhotoBrowserCollectionViewCell
        //取出cell里面的图片
        guard let picture = cell.imageV.image else {
        return
        }
        //保存图片
        UIImageWriteToSavedPhotosAlbum(picture, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image : UIImage, didFinishSavingWithError error : NSError?, contextInfo : AnyObject) {
        let message = error != nil ? "保存失败" : "保存成功"
        SVProgressHUD.showInfoWithStatus(message)
    }
}

// MARK:-collectionView数据源方法
extension PhotoBrowserController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureUrls!.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoBrowserCellId, forIndexPath: indexPath) as! PhotoBrowserCollectionViewCell
        
        cell.pictureUrl = pictureUrls![indexPath.item]
        
        return cell
    }
}

class PhotoBrowserCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        //布局属性
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
        //collectionView属性
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}
